package cn.ym.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.ym.domain.Param;
import cn.ym.domain.User;
import cn.ym.exception.BusinessException;
import cn.ym.mapper.ParamMapper;
import cn.ym.query.ParamQuery;
import cn.ym.service.ParamService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 参数的业务层
 */
@Service
public class ParamServiceImpl implements ParamService {

    @Autowired
    private ParamMapper paramMapper;

    @Override
    public void add(Param param, HttpSession session) {
        //空值检验
        if(StrUtil.isEmptyIfStr(param.getParamKey())){
            throw new BusinessException("亲：参数键不能为空");
        }
        if(StrUtil.isEmptyIfStr(param.getParamDesc())){
            throw new BusinessException("亲：参数描述不能为空");
        }


        //从我们设置的session登录信息里面获取登陆人名称
        User user = (User)session.getAttribute("user_in_session");
        String realName = user.getRealName();
        //设置用户名
        param.setUpdateUserName(realName);
        paramMapper.add(param);
    }

    @Override
    public void update(Param param, HttpSession session) {
        //空值检验
        if(StrUtil.isEmptyIfStr(param.getParamKey())){
            throw new BusinessException("亲：参数键不能为空");
        }
        if(StrUtil.isEmptyIfStr(param.getParamDesc())){
            throw new BusinessException("亲：参数描述不能为空");
        }

        //从我们设置的session登录信息里面获取登陆人名称
        User user = (User)session.getAttribute("user_in_session");
        String realName = user.getRealName();
        //设置用户名
        param.setUpdateUserName(realName);
        paramMapper.update(param);
    }

    @Override
    public void delete(Long id) {
        paramMapper.delete(id);
    }
    @Override
    public void Patchdel(Long[] ids) {
        paramMapper.Patchdel(ids);
    }



    //获取qq--wx社交所有参数信息
    @Override
    public Map<String,Object> getAllParam() {
        //查询所有
        List<Param> params = paramMapper.findAll();

        Map<String, Object> map = new HashMap<>();
        for (Param param : params) {
            map.put(param.getParamKey(),param.getParamValue());
        }
        return map;
    }

    @Override
    public Param findOne(Long id) {
        return paramMapper.findOne(id);
    }

    @Override
    public List<Param> findAll() {
        return paramMapper.findAll();
    }

    @Override
    public List<Param> queryPage(ParamQuery paramQuery) {
        //开启分页
        /**1.自动计算总数量
         * 2.根据驱动名计算 limit的第一个参数
         * 3.分页返回结果
         */
       PageHelper.startPage(paramQuery.getCurrentPage(), paramQuery.getPageSize());
       return paramMapper.queryPage(paramQuery);
    }
}